package Day2025_01_22;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.BindException;
import java.net.Socket;
import java.util.Scanner;

public class TCPEchoClient {
    // 声明Socket对象
    private Socket socket;

    /**W
     * 构造方法
     * @param serverIp 服务器IP
     * @param serverPort 服务器端口号
     * @throws IOException
     */
    public TCPEchoClient (String serverIp, int serverPort) throws IOException {
        // 检验
        if (serverIp == null || serverIp.isEmpty()) {
            throw new RuntimeException("Ip的机子不能为空.");
        }


        if (serverPort < 1025 || serverPort > 65535) {
            throw new BindException("端口号必须在1025 ~ 65535之间.");
        }
        // 根据服务器Ip和端口号初始化Socket对象
        this.socket = new Socket(serverIp, serverPort);
    }




    public void start () {
        System.out.println("客户端已启动.");
        // 从Socket对象中获取输入与输出流对象
        try (InputStream inputStream = this.socket.getInputStream();
             OutputStream outputStream = this.socket.getOutputStream()) {
            // 1. 循环接受用户的输入
            while (true) {
                System.out.println("->");
                Scanner scanner = new Scanner(System.in);
                String request = scanner.nextLine();
                // 非空检验
                if (request == null || request.isEmpty()) {
                    System.out.println("输入的内容不能为空.");
                    continue;
                }
                // 2. 把用户的输入封装到输出流中, 可以用PrintWriter进行简写
                PrintWriter writer = new PrintWriter(outputStream);
                // 3. 把数据写入到输出流中
                writer.println(request);
                // 4. 强制刷新缓冲区, 到此请求发送完成
                writer.flush();
                // 5. 准备接收服务器返回的响应数据, 通过输入流创建用于读取响应的对象
                Scanner responseScanner = new Scanner(inputStream);
                // 6. 解析响应数据
                String response = responseScanner.nextLine();
                // 7. 打印日志
                System.out.printf("request = %s, response = %s\n", request, response);
                // 关闭流之后表示客户端下线了
//                scanner.close();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws IOException {
        TCPEchoClient client = new TCPEchoClient("127.0.0.1" ,9090);
        client.start();
    }
}
